<?php

namespace app\common\model;

use addons\inform\controller\Inform;
// use app\common\controller\BackoutOrder;
use app\common\library\Sms;
// use think\Db;
use think\Exception;
use fast\Time;
use think\Model;

class Voucher extends Model
{

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = '';
    
    const STATUS_NO      = 0;    //未验证
    const STATUS_YES     = 1;    //已验证
    const USE_STATUS_NO  = 0;    //不可以使用
    const USE_STATUS_YES = 1;    //可以使用


    /**
     * [voucherNumber 生产凭证号]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @return   [type]      [description]
     */
    protected function voucherNumber()
    {
        $rund_num = unique_rand(100000, 400000, 5);

        return (ceil(time() / 10000) + $rund_num[rand(0, 4)]) . rand(1, 9);
    }

    /**
     * [createVoucher 创建凭证号]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    array       $data [description]
     * @param    [type]      $num  [description]
     * @return   [type]            [description]
     */
    public function createVoucher(array $data, $num)
    {

        $data['voucher_number'] = $this->voucherNumber();
        $data['no_check_num']   = $data['buynum'];

        try {
            $rest = $this->allowField(true)->save($data);
            $voucher_id = $this->id;
            $this->addOrderGoods($num, $data['voucher_number'], $data['order_id'],$voucher_id);
            
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        return $rest;
    }

    /**
     * [addOrderGoods 添加订单项]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $code       [description]
     * @param    [type]      $num        [description]
     * @param    [type]      $voucher_no [description]
     * @param    [type]      $order_id   [description]
     */
    public function addOrderGoods($num, $voucher_no, $order_id,$voucher_id)
    {
        $order = Order::get(['id' => $order_id]);
        $data = [
            'order_id'      => $order_id,
            'voucher_id'    => $voucher_id,
            'voucher_no'    => $voucher_no,
            'goods_id'      => $order['goods_id'],
            'price'         => $order['goods_price'],
            // 'goods_name'    => $order['product_name'],
            'buy_nums'      => $num,
            'amount'        => $order['order_amount']
        ];
        $orderGoods = new OrderGoods();
        if ($num > 1) {
            for ($i = 0; $i < $num; $i++) {
            $dataArray[$i] = $data;
           }
           $orderGoods->allowField(true)->saveAll($dataArray);
        }else{
           $orderGoods->allowField(true)->save($data); 
        }
    }


    /**
     * [downState 更改凭证号不可用状态]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $order_id [description]
     * @param    [type]      $num      [description]
     * @return   [type]                [description]
     */
    public function downState($order_id, $num)
    {

        $voucher = Voucher::get(['order_id' => $order_id]);
        if ($voucher['no_check_num'] == $num) {
            //全部
            $voucher->no_check_num = $num;
            $voucher->use_status = 0;
            $voucher->save();
        } else {
            $voucher->setDec('no_check_num', $num);
        }

    }


    /**
     * [changeState 取消退款，恢复凭证号使用状态]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $order_id [description]
     * @param    [type]      $num      [description]
     * @return   [type]                [description]
     */
    public function changeState($order_id, $num)
    {
        try {
            $voucher = Voucher::get(['order_id' => $order_id]);
            if (!$voucher->use_status) {
                $voucher->use_status = 1;
                $voucher->save();
            }
        } catch (Exception $e) {
            \exception($e->getMessage());
        }

    }


    /**
     * [check 凭证号、门票验证规则]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $voucher     [description]
     * @param    [type]      $consume_num [description]
     * @return   [type]                   [description]
     */
    public function check($voucher,$consume_num)
    {   

    	//第三方码
    	if ($voucher['is_thirdparty']) {
    		 exception('第三方码只能通过第三方设备验证');
    	}
        $now = time();//当前时间戳
        list($day_start,$day_end) = Time::today();
        $order = Order::get(['id' => $voucher['order_id']]);
        $goods = Goods::get(['id' => $order['goods_id']]);
        $start_time = $goods->join_time($now,$goods['check_start_time']);//验票开始时间
        $end_time   = $goods->join_time($now,$goods['check_end_time']);//验票结束时间
        if ($now > $end_time){
            //验票结束
            exception('今日验票已结束');
        }
        if ($now < $start_time){
            //验票未开始
            $start_time = datetime($start_time);
            exception('请于'.$start_time.'之后验票');
        }
        if ($consume_num > $voucher['no_check_num']) {
            exception('验票数量与实际购买票数不符合');
        }
        //有效期：当日有效
        if ($day_start !== $order['play_time']  && $goods['deadlineType'] == Goods::DEADLINETYPE_0){
            exception('该票使用时间为:'.datetime($order['play_time'],'Y-m-d'));
        }
        //有效期：自定有效期
        if ($goods['deadlineType'] == Goods::DEADLINETYPE_2){
            $now_week    = date('w');//当前周几
            $valid_start = $goods['valid_period_start'];//生效时间
            $valid_end   = $goods['valid_period_end'];//结束时间
            $valid_week  = $goods['valid_period_week'];
            if ($day_start < $valid_start || $day_start > $valid_end){
                //当前时间小于生效时间或结束时间大于当前时间,该票无法使用
                $msg = '该票使用时间'.datetime($valid_start,'Y-m-d').'至'.datetime($valid_end,'Y-m-d');
                exception($msg);
            }
            //当前时间是否在可用时间内
            if (!in_array($now_week,$valid_week)){
                $str_week = $goods->getValidPeriodWeekTextAttr('',$goods);
                $msg = '请在'.$str_week.'任选一天游玩';
                exception($msg);
            }
        }elseif ($goods['deadlineType'] == Goods::DEADLINETYPE_1){
            //游玩日期当日及前后几天有效
            $play_time   = $order['play_time'];
            $front       = $goods['deadlineFront'];
            $later       = $goods['deadlineLater'];
            $valid_start = strtotime("- $front Day",$play_time);//生效时间
            $valid_end   = strtotime("+ $later Day",$play_time);//结束时间
            if ($day_start < $valid_start || $day_start > $valid_end){
                //当前时间小于生效时间或结束时间大于当前时间,该票无法使用
                $msg = '该票使用时间'.datetime($valid_start,'Y-m-d').'至'.datetime($valid_end,'Y-m-d');
                exception($msg);
            }
        }
        // if ($goods['before'] == 1){
        //     //提前几小时购买，票只能在几小时后使用
        //     $minute = $goods['beforeHour'] * 60;
        //     $minute = $minute + $goods['beforeMinute'];
        //     $check_time   = strtotime("+ $minute Minute",$order['add_time']);
        //     if ($check_time > $now){
        //         $check_time = datetime($check_time);
        //         exception('该票需'.$check_time.'后使用');
        //     }
        // }

    }


    /**
     * [beforeHoure 提前x小时购买，票只能在几小时后使用]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    array       $goods [description]
     * @param    array       $order [description]
     * @return   [type]             [description]
     */
    protected function beforeHoure($goods = [], $order = [])
    {
        if ($goods['before'] !== 1){
            return;
        }
        $now    = time();
        $minute = $goods['beforeHour'] * 60;
        $minute = $minute + $goods['beforeMinute'];
        $check_time   = strtotime("+ $minute Minute",$order['add_time']);
        if ($check_time > $now){
            $check_time = datetime($check_time);
            exception('该票需'.$check_time.'后使用');
        }
    }

    /**
     * [checkVoucher 验证凭证号]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    array       $voucher     [description]
     * @param    [type]      $consume_num [description]
     * @param    integer     $devices_id  [description]
     * @return   [type]                   [description]
     */
    public function checkVoucher($voucher = [], $consume_num, $devices_id = 0)
    {
        $order = Order::get(['id' => $voucher['order_id']]);
        $order_goods = new OrderGoods();
        $update = [
            'consum'       => $voucher['consum'] + $consume_num,
            'no_check_num' => $voucher['no_check_num'] - $consume_num,
            'check_time'   => time(),
        ];
        if ($consume_num == $voucher['no_check_num']) {
            //要验证数量与未验证数量相等为全部验证完
            $update['use_status'] = self::USE_STATUS_NO;
        }
        //已经验证
        if (!$voucher['status']) {
            $update['status']  = self::STATUS_YES;
        }
        $log_data = [
            'voucher_id'  => $voucher['id'],
            'voucher_num' => $consume_num,
            'order_id'    => $voucher['order_id'],
            'scenic_id'   => $voucher['scenic_id'],
            'goods_id'    => $order['goods_id'],
            'store_id'    => $order['store_id'],
            'user_id'     => $order['user_id'],
            'devices_id'  => $devices_id,
            'add_time'    => date('Y-m-d H:i:s'),
            'create_time' => time()
        ];
        try {

            $this->where('id',$voucher['id'])->update($update);
            Voucherlog::create($log_data);       //凭证号日志
            $order_goods->checkTicket($voucher['voucher_number'], $consume_num,$voucher['order_id']);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }

    }

    /**
     * [expired 凭证号过期]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $order_id [description]
     * @return   [type]                [description]
     */
    public function expired($order_id)
    {
        $where = ['order_id' => $order_id,'status' => self::STATUS_NO];
        $this->where($where)->update(['use_status' => self::USE_STATUS_NO]);
    }



    /**
     * [sendSms 发送凭证号]
     * @Author   ZhouYunpeng
     * @DateTime 2021-11-11
     * @param    [type]      $order [description]
     * @param    [type]             [description]
     */
    public function sendSms($order)
    {   
        
        if ($order['order_phone']) {

            $voucher = $this->where(['order_id'=>$order['id']])
                   ->alias('v')
                   ->join('scenic s','s.id = v.scenic_id','LEFT')
                   ->join('goods g','g.id = '.$order['goods_id'],'LEFT')
                   ->field('voucher_number,goods_name,scenic_name,message_content,notifyCustomer')
                   ->find();
            if ($voucher['notifyCustomer']) {
                $code = $voucher['voucher_number'];
                $content = '凭证号:'.$code.'有效期:'.$order['play_time_notes'].'您已成功购买'.$voucher['scenic_name'].':'.$voucher['goods_name'].'('.$order['ticket_num'].')张'.$voucher['message_content'];

                $ret =  Sms::sms_send2($order['order_phone'], $content);
                if ($ret === false){
                    // savelog('短息发送失败',$ret);
                }else{
                    return $ret;
                }
            }
        }

    }

    /**
     * [resendSms 重发信息]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $order_id [description]
     * @param    [type]      $phone    [description]
     * @return   [type]                [description]
     */
    public function resendSms($order_id, $phone)
    {
       $result = Inform::userBooking($order_id);
       return $result;
    }

    /***
     * @param $order_id
     * @throws \think\exception\DbException
     * 余额,授信支付回调
     */
    public static function notify($order_id)
    {
        $order = Order::get(['id' => $order_id]);

        $model = new static;
        if ($order['pay_status']){
            $voucher = [
                'order_id'    => $order['id'],
                'sell_id'     => $order['sell_id'],
                'user_id'     => $order['user_id'],
                'scenic_id'   => $order['scenic_id'],
                'user_phone'  => $order['order_phone'],
                'buynum'      => $order['ticket_num'],
                'status'      => 0,
                'create_time' => time()
            ];
            $model->createVoucher($voucher, $order['ticket_num']);
            $model->sendSms($order);
        }

    }

}